const {
  db
} = require('../core/db.js');

const { LikeError, DislikeError } = require('../core/httpError.js');

const { Art } = require('./art.js');
const {
  Sequelize,
  Model,
  HostNotFoundError,
  Op
} = require('sequelize');
class Favor extends Model {
  static async like (art_id, type, uid) {
    const favor = await Favor.findOne({
      where: {
        art_id,
        type,
        uid
      }
    });
    if (favor) {
      throw new LikeError();
    };

    return db.transaction(async t => {
      console.log('t', t);
      await Favor.create({
        art_id,
        type,
        uid
      }, { transaction: t });
      // const art = Art.getData(art_id, type);
      // console.log('art123456', art);

      // Movie.findOne(finder)

      // await art.increment('fav_nums', { by: 1, transaction: t });
      // await t.commit();
    });

  }

  static async dislike (art_id, type, uid) {
    // 关系数据库 ACID

    const favor = await Favor.findOne({
      where: {
        art_id,
        type,
        uid
      }
    });

    if (!favor) {
      throw new DislikeError();
    };
    console.log('resutl', favor);

    return db.transaction(async t => {
      // await Favor.destroy({
      //   force: false, // false 软删除
      //   transaction: t
      // });
      await favor.destroy({
        force: false,
        transaction: t
      })
      const art = Art.getData(art_id, type);
      console.log('art123456', art);
      await art.decrement('fav_nums', { by: 1, transaction: t });
    });

  }

  static async userLikeIt (art_id, type, uid) {
    const favor = await Favor.findOne({
      where: {
        art_id,
        type,
        uid
      }
    })
    return !!favor;
  }

  static async getMyClassicFavors (uid) {
    // type != 400
    const arts = await Favor.findAll({
      where: {
        uid,
        type: {
          [Op.not]: 400
        }
      }
    });

    if (!arts) {
      // throw new NotFound();
    };

    return await Art.getList(arts);
  }
}

Favor.init({
  uid: Sequelize.INTEGER,
  art_id: Sequelize.INTEGER,
  type: Sequelize.INTEGER
}, {
  sequelize: db,
  tableName: 'favor'
});

module.exports = {
  Favor
};